import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import 'Pet.dart';
import 'PetsDetail.dart';

class ChatDetailPage extends StatefulWidget {
  final String friendName;
  final String friendAvatar;
  final List<String> initialMessages;
  final ValueNotifier<Map<String, String>> lastMessageNotifier;
  final int friendIndex;
  final void Function(List<String>) updateMessagesCallback; // 新增回调函数
  final Map<String, String>? petInfo; // 新增宠物信息

  const ChatDetailPage({
    Key? key,
    required this.friendName,
    required this.friendAvatar,
    this.initialMessages = const [],
    required this.lastMessageNotifier,
    required this.friendIndex,
    required this.updateMessagesCallback, // 初始化
    this.petInfo,// 初始化宠物信息
  }) : super(key: key);

  @override
  _ChatDetailPageState createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  final TextEditingController _messageController = TextEditingController();
  late List<String> _messages;

  @override
  void initState() {
    super.initState();
    _messages = List<String>.from(widget.initialMessages); // 复制历史消息

    // 如果有宠物信息，将其添加为消息
    if (widget.petInfo != null) {
      _messages.add("查看宠物信息: ${widget.petInfo!['url']}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Row(
          children: [
            CircleAvatar(
              backgroundImage: AssetImage(widget.friendAvatar),
            ),
            const SizedBox(width: 10),
            Text(widget.friendName),
          ],
        ),
      ),
      body: Column(
        children: [
          // 聊天消息列表
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final isPetInfo = widget.petInfo != null && index == _messages.length - 1;

                return ListTile(
                  title: Align(
                    alignment: Alignment.centerRight, // 将消息右对齐
                    child: Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade100,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(_messages[index]), // 显示消息
                    ),
                  ),
                  onTap: isPetInfo
                      ? () {
                    // 跳转到 PetsDetailPage 查看宠物详细信息
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => PetsDetailPage(
                          pet: Pet(
                            name: widget.petInfo!['name']!,
                            url: widget.petInfo!['url']!,
                            petType: 1,
                            engName: '',
                            characters: '',
                            nation: '',
                            easyOfDisease: '',
                            life: '',
                            price: '',
                            desc: '',
                            feature: '',
                            characterFeature: '',
                            careKnowledge: '',
                            feedPoints: '',
                            coverURL: '',
                          ),
                          friends: [],
                        ),
                      ),
                    );
                  }
                      : null,
                );
              },
            ),
          ),
          const Divider(),
          // 输入框和发送按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 6.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    onChanged: (text) {
                      setState(() {}); // 更新UI以显示或隐藏发送按钮
                    },
                    decoration: InputDecoration(
                      // hintText: '输入消息...',
                      isDense: true,  // 让输入框高度更小
                      contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      // contentPadding: const EdgeInsets.symmetric(horizontal: 15.0),
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                // 仅在有输入时显示“发送”按钮
                if (_messageController.text.isNotEmpty)
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      //primary: Theme.of(context).primaryColor,
                      backgroundColor: Colors.blue,
                    ),
                    onPressed: _sendMessage,
                    child: const Text(
                      '发送',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 10),
          // 底部操作按钮行
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Icon(Icons.mic, color: Colors.grey),
                Icon(Icons.image, color: Colors.grey),
                Icon(Icons.camera_alt, color: Colors.grey),
                Icon(Icons.card_giftcard, color: Colors.grey),
                Icon(Icons.emoji_emotions, color: Colors.grey),
                Icon(Icons.add_circle_outline, color: Colors.grey),
              ],
            ),
          ),
          const SizedBox(height: 12),
        ],
      ),
    );
  }

  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    if (now.difference(dateTime).inDays == 0) {
      // 当天消息显示小时和分钟
      return DateFormat.Hm().format(dateTime);
    } else {
      // 非当天显示年月日
      return DateFormat('yyyy/MM/dd').format(dateTime);
    }
  }

  // 发送消息
  void _sendMessage() {
    if (_messageController.text.isNotEmpty) {
      final newMessage = _messageController.text;
      setState(() {
        _messages.add(newMessage); // 添加新消息
        _messageController.clear(); // 清空输入框
      });

      // 更新 lastMessageNotifier 的值
      // final currentTime = DateTime.now();
      final formattedTime = _formatTime(DateTime.now());
      widget.lastMessageNotifier.value = {
        'name': widget.friendName,
        'lastMessage': newMessage,
        'time': formattedTime,
      };

      // 更新 MessagePage 中对应好友的 messages 列表
      // widget.friends[widget.friendIndex]['messages'] = _messages;
      // 调用回调函数，将消息传递回 MessagePage
      widget.updateMessagesCallback(_messages);

    }
  }
}


// import 'package:flutter/material.dart';
// import 'PetsDetail.dart';
// import 'Pet.dart';
//
// class ChatDetailPage extends StatefulWidget {
//   final String friendName;
//   final String friendAvatar;
//   final List<String> initialMessages;
//   final ValueNotifier<Map<String, String>> lastMessageNotifier;
//   final int friendIndex;
//   final void Function(List<String>) updateMessagesCallback; // 新增回调函数
//   final Map<String, String>? petInfo; // 新增宠物信息
//
//   const ChatDetailPage({
//     Key? key,
//     required this.friendName,
//     required this.friendAvatar,
//     this.initialMessages = const [],
//     required this.lastMessageNotifier,
//     required this.friendIndex,
//     required this.updateMessagesCallback, // 初始化
//     this.petInfo,// 初始化宠物信息
//   }) : super(key: key);
//
//   @override
//   _ChatDetailPageState createState() => _ChatDetailPageState();
// }
//
// class _ChatDetailPageState extends State<ChatDetailPage> {
//   final TextEditingController _messageController = TextEditingController();
//   late List<String> _messages;
//
//   @override
//   void initState() {
//     super.initState();
//     _messages = List<String>.from(widget.initialMessages); // 复制历史消息
//
//     // 如果有宠物信息，将其添加为消息
//     if (widget.petInfo != null) {
//       _messages.add("查看宠物信息: ${widget.petInfo!['name']}");
//     }
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         backgroundColor: Colors.blue,
//         title: Row(
//           children: [
//             CircleAvatar(
//               backgroundImage: AssetImage(widget.friendAvatar),
//             ),
//             const SizedBox(width: 10),
//             Text(widget.friendName),
//           ],
//         ),
//       ),
//       body: Column(
//         children: [
//           // 聊天消息列表
//           Expanded(
//             child: ListView.builder(
//               itemCount: _messages.length,
//               itemBuilder: (context, index) {
//                 final isPetInfo = widget.petInfo != null && index == _messages.length - 1;
//
//                 return ListTile(
//                   title: Align(
//                     alignment: Alignment.centerRight, // 将消息右对齐
//                     child: Container(
//                       padding: const EdgeInsets.all(10),
//                       decoration: BoxDecoration(
//                         color: Colors.blue.shade100,
//                         borderRadius: BorderRadius.circular(10),
//                       ),
//                       child: Text(_messages[index]), // 显示消息
//                     ),
//                   ),
//                   onTap: isPetInfo
//                       ? () {
//                     // 跳转到 PetsDetailPage 查看宠物详细信息
//                     Navigator.push(
//                       context,
//                       MaterialPageRoute(
//                         builder: (context) => PetsDetailPage(
//                           pet: Pet(
//                             name: widget.petInfo!['name']!,
//                             url: widget.petInfo!['url']!,
//                             petType: 1,
//                             engName: '',
//                             characters: '',
//                             nation: '',
//                             easyOfDisease: '',
//                             life: '',
//                             price: '',
//                             desc: '',
//                             feature: '',
//                             characterFeature: '',
//                             careKnowledge: '',
//                             feedPoints: '',
//                             coverURL: '',
//                           ),
//                           friends: [],
//                         ),
//                       ),
//                     );
//                   }
//                       : null,
//                 );
//               },
//             ),
//           ),
//           // 输入框和发送按钮
//           Padding(
//             padding: const EdgeInsets.all(8.0),
//             child: Row(
//               children: [
//                 Expanded(
//                   child: TextField(
//                     controller: _messageController,
//                     decoration: const InputDecoration(
//                       hintText: '输入消息...',
//                     ),
//                   ),
//                 ),
//                 IconButton(
//                   icon: const Icon(Icons.send),
//                   onPressed: () {
//                     setState(() {
//                       _messages.add(_messageController.text); // 添加消息到列表
//                     });
//                     widget.updateMessagesCallback(_messages);
//                     _messageController.clear();
//                   },
//                 ),
//               ],
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
